package com.jichangxiu.framework.action;

import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import com.jichangxiu.common.annotation.Get;
import com.jichangxiu.common.annotation.Rest;
import com.jichangxiu.common.cache.RedisService;
import com.jichangxiu.common.constant.RedisKeys;
import com.jichangxiu.common.entity.bo.Record;
import com.jichangxiu.common.exception.FrameworkException;
import com.jichangxiu.common.properties.JcxProperties;
import com.jichangxiu.common.utils.EncodeUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * CaptchaAction:
 *
 * @author Jcx
 * @create 2023-04-04 10:06
 */
@Slf4j
@Rest("/platform/captcha")
@Tag(name = "平台-登录验证码控制器")
public class CaptchaAction {

    @Resource
    private Producer producer;

    @Resource
    private RedisService redisService;

    @Resource
    private JcxProperties jcxProperties;

    @Get("/createLoginCaptcha")
    @Operation(summary = "平台-创建登录验证码")
    public Record createLoginCaptcha() {
        try {
            // 送给前端的
            String captchaKey = IdUtil.nanoId();
            // 验证码内容
            String captchaCode = producer.createText();
            // 生成图片
            BufferedImage image = producer.createImage(captchaCode);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            String str = "data:image/jpeg;base64,";
            String base64Img = str + EncodeUtils.encodeBase64(outputStream.toByteArray());
            redisService.setCacheObject(RedisKeys.createCodeToCaptcha(captchaKey), captchaCode, 120L, TimeUnit.SECONDS);
            return Record.getRecord(jcxProperties.getLoginProperties().getToBrowserCaptchaKey(), captchaKey).set(jcxProperties.getLoginProperties().getParamCaptchaCode(), captchaCode).set(jcxProperties.getLoginProperties().getToBrowserCaptchaImage(), base64Img);
        } catch (IOException ex) {
            log.error("验证码生成异常", ex);
            throw FrameworkException.build("验证码生成异常", ex);
        }
    }

}
